import os

import time

from FastFitsFileTools.FitsTools import Fits, Fitscut
from FastFitsFileTools.FitsTools.FitsMerge import FitsMerge
from FastFitsFileTools.FitsTools.FitsOutput import wirtreToFileForFast


def usage():
    print """

"-a", "file1:      [please give ***path/filename***]"
"-b", "file2:      [please give ***path/filename***]"
"-o", "output:    [output path]"

"""

def readPath(filename):
    while 1:
        files = filename.split('/')[len(filename.split('/')) - 1]

        filename2 = files[:len(files) - 9]+ str('%04d' % (int(files[len(files) - 9:len(files) - 5]) + 1))+'.fits'
        #print filename2
        filename2_path='/'
        for i in [x + 1 for x in range(filename.split('/').__len__() - 2)]:
            filename2_path+=(filename.split('/')[i]+'/')

        filename2=filename2_path+filename2
        print filename2
        if os.path.exists(filename2) and os.path.getsize(filename2)>2000000000:
            return filename2
            break;
        else:
            sys.exit()
            #readPath(filename)

def exeMergeFits(filename1,filename2,outpath):
    #while 1:
    #    nextfile=readPath(filename1)
     #   if nextfile == filename2:
    fits1 = Fits(filename1)
    #fits_merged = fits1
    fits2 = Fits(filename2)
                # fits.centerFreq = (startfreq + endfreq) / 2

        #     fmerge = FitsMerge(fits_merged, fits2, 0, 0, 0)
        #     break;
        # else:
        #     fits1 = Fits(filename1)
        #     fits_merged = fits1
        #     fits2 = Fits(nextfile)
        #     # fits.centerFreq = (startfreq + endfreq) / 2

    fmerge = FitsMerge(fits1, fits2, 0, 0, 0)



        # self.mergePolae(0)
    fits_merged=fmerge.merge()

    wirtreToFileForFast(fits_merged,outpath)


if __name__ == '__main__':
    import getopt, sys

    try:
        opts, args = getopt.getopt(sys.argv[1:], "a:b:o:",
                                   ["file1=", "file2=", "output="])

    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)
    if len(sys.argv) == 1:
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-a", "--file1"):
            filename1 = str(a)
        if o in ("-b", "--file2"):
            filename2 = str(a)
        if o in ("-o", "--output"):
            outpath = str(a)




    exeMergeFits(filename1, filename2, outpath)
